<?php

namespace app\index\controller\wanlshop;

use fast\Random;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;
use app\common\controller\Backend;

/**
 * 会员管理
 *
 * @icon fa fa-user
 */
class User extends Backend
{
    protected $noNeedLogin = '';
    protected $noNeedRight = '*';
    protected $relationSearch = true;
    protected $searchFields = 'id,username,nickname';

    /**
     * @var \app\admin\model\User
     */
    protected $model = null;

    public function _initialize()
    {
//        parent::_initialize();
        $this->model = model('app\admin\model\User');
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            dump($where);exit;
            $list = $this->model
                ->with(['group','semester'])
                ->where($where)
//                ->where('identity','in',[0,1])
                ->order($sort, $order)
                ->paginate($limit);
            foreach ($list as $k => $v) {
                $v->avatar = $v->avatar ? cdnurl($v->avatar, true) : letter_avatar($v->nickname);
                $v->hidden(['password', 'salt']);
            }
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 获取会员列表
     * @return void
     */
    public function get_list()
    {
        $identity = $this->request->request('identity');
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->model
                ->with('group')
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);
            foreach ($list as $k => $v) {
                $v->avatar = $v->avatar ? cdnurl($v->avatar, true) : letter_avatar($v->nickname);
                $v->hidden(['password', 'salt']);
            }
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
    }


    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $this->token();
        }
        return parent::add();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('groupList', build_select('row[group_id]', \app\admin\model\UserGroup::column('id,name'), $row['group_id'], ['class' => 'form-control selectpicker']));
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }

            if($row->identity != $params['identity']){
                if($params['identity'] == 2){//学生或家长更换为老师
                    $data = [];
                    $data['username'] = $row->mobile;
                    $data['teacher_id'] = $row->id;
                    $data['nickname'] = $params['nickname'];
                    $data['salt'] = Random::alnum();
                    $data['password'] = md5(md5('a123456') . $data['salt']);
                    $data['avatar'] = '/assets/img/avatar.png'; //设置新管理员默认头像。
                    $data['is_main'] = 1;

                    $Manystore = new Manystore();
                    $ManystoreId = $Manystore->insertGetId($data);
                    if (!$ManystoreId) {
                        $this->error('修改失败');
                    }

                    $manystoreAuthGroupModel = new ManystoreAuthGroup();
                    $group = [];
//                    $group['shop_id'] = $this->shopModel->id;
                    $group['name'] = '超级管理员';
                    $group['rules'] = '*';
                    $group['createtime'] = time();
                    $group['updatetime'] = time();
                    $group_id = $manystoreAuthGroupModel->insertGetId($group);
                    if(!$group_id){
                        $this->error('添加失败');
                    }

                    $manystoreAuthGroupAccessModel = new ManystoreAuthGroupAccess();
                    $group_access = [];
                    $group_access['uid'] = $ManystoreId;
                    $group_access['group_id'] = $group_id;

                    $manystoreAuthGroupAccessModel->insert($group_access);

                }elseif ($row->identity == 2 && $params['identity'] < 2){//老师更换为学生
                    //删除manystore表数据
                    Manystore::where('teacher_id',$row->id)->delete();
                }
            }
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        $row = $this->model->get($ids);
        $this->modelValidate = true;
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        Auth::instance()->delete($row['id']);
        $this->success();
    }

}
